import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../pojo/Enums.dart';
import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../bloc/LoginCubit.dart';
import 'LoadingView.dart';
import 'component/UiUtil.dart';
import 'component/login/PasswordLoginView.dart';
import 'component/login/PatternLockView.dart';
import 'component/login/ScanLockView.dart';
import 'component/login/TokenLoginView.dart';

class LoginView extends StatelessWidget {
  final String tenantCode;
  final String loginSuccessUrl;
  final bool isShowTitle;

  const LoginView({required this.tenantCode, required this.loginSuccessUrl, this.isShowTitle = true, super.key});

  @override
  Widget build(BuildContext context) {
    final state = context.watch<LoginCubit>().state;
    return LoadingView(state: state.state, child: _buildForm(context));
  }

  Widget _buildForm(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 50, right: 50),
      child: Column(
        children: [
          const SizedBox(
            height: 80,
          ),
          _buildTitle(context),
          _buildLoginUserPane(context),
          Expanded(child: this._buildBody(context)),
        ],
      ),
    );
  }

  Widget _buildTitle(BuildContext context) {
    final loginCubit = context.read<LoginCubit>();
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Expanded(
            child: Offstage(
                offstage: !this.isShowTitle,
                child: Center(
                  child: Text(
                    '宇连通客户端登录',
                    style:
                        TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: ImConstant.IM_LOGIN_DEFAULT_COLOR),
                  ),
                ))),
        PopupMenuButton<LoginType>(
          tooltip: '请选择登录方式',
          onSelected: (LoginType loginType) {
            loginCubit.add(new LoginSelectLoginType(loginType));
          },
          icon: _buildSvg(loginCubit.state.popupMoreIcon),
          itemBuilder: (BuildContext context) {
            return [
              PopupMenuItem<LoginType>(
                value: LoginType.password,
                child: _buildMenuItem('密码登录', 'assets/svg/password.svg'),
              ),
              PopupMenuItem<LoginType>(
                value: LoginType.slidePassword,
                child: _buildMenuItem('刷屏登录', 'assets/svg/pattern-lock.svg'),
              ),
              PopupMenuItem<LoginType>(
                value: LoginType.scanLock,
                child: _buildMenuItem('扫码登录', 'assets/svg/qrcode.svg'),
              ),
            ];
          },
        ),
      ],
    );
  }

  Widget _buildLoginUserPane(BuildContext context) {
    final loginCubit = context.read<LoginCubit>();
    return Visibility(
      visible: loginCubit.state?.currentImLogin != null,
      replacement: const SizedBox(
        height: 81,
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 1),
        child: Center(
            child: Column(
          children: [
            MenuAnchor(
              builder: (
                BuildContext context,
                MenuController controller,
                Widget? child,
              ) => _buildUserImage(loginCubit.state.currentImLogin, controller),
              menuChildren: loginCubit.state.logins.map((imLogin) {
                return MenuItemButton(
                  child: Text(imLogin.userId, style: TextStyle(color: ImConstant.IM_LOGIN_DEFAULT_COLOR)),
                  onPressed: () {
                    loginCubit.add(new LoginSelectUser(imLogin));
                  },
                );
              }).toList(),
            ),
            Text(
              loginCubit.state.currentImLogin?.userId ?? '',
              style: TextStyle(color: ImConstant.IM_LOGIN_DEFAULT_COLOR),
            ),
          ],
        )),
      ),
    );
  }

  Widget _buildUserImage(ImLogin? imLogin, MenuController controller) {
    return GestureDetector(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(30),
        child: const Image(
          image: AssetImage('assets/img/head.jpg'),
          width: 60,
          height: 60,
        ),
      ),
      onTap: () {
        if (controller.isOpen) {
          controller.close();
        } else {
          controller.open();
        }
      },
    );
  }

  Widget _buildBody(BuildContext context) {
    final state = context.watch<LoginCubit>().state;
    ImLogin? imLogin = state.currentImLogin;
    if (state.loginType == LoginType.password) {
      return PasswordLoginView(loginSuccessUrl: this.loginSuccessUrl, tenantCode: this.tenantCode);
    } else if (state.loginType == LoginType.token) {
      return TokenLoginView(loginSuccessUrl: this.loginSuccessUrl, tenantCode: this.tenantCode);
    } else if (state.loginType == LoginType.slidePassword) {
      return PatternLockView(loginSuccessUrl: this.loginSuccessUrl, tenantCode: this.tenantCode);
    } else if (state.loginType == LoginType.scanLock) {
      return ScanLockView(loginSuccessUrl: this.loginSuccessUrl, tenantCode: this.tenantCode);
    }
    throw Exception("不支持登录方式：" + state.loginType!.name ?? '');
  }

  Widget _buildSvg(String assetFile) {
    return buildSvgView(assetFile, ImConstant.IM_LOGIN_TYPE_ICON_SIZE, ImConstant.IM_LOGIN_TYPE_ICON_SIZE,
        ImConstant.IM_LOGIN_DEFAULT_COLOR);
  }

  Widget _buildMenuItem(String name, String assetsFile) {
    // return ListTile(leading: _buildSvg(assetsFile), title: Text(name, style: TextStyle(color: ImConfig.IM_LOGIN_DEFAULT_COLOR),),);
    return Row(
      children: [
        _buildSvg(assetsFile),
        Padding(
          padding: EdgeInsets.only(left: 10),
          child: Text(
            name,
            style: TextStyle(color: ImConstant.IM_LOGIN_DEFAULT_COLOR),
          ),
        ),
      ],
    );
  }
}
